#!/bin/bash

# TODO: Use getopts?
# TODO: rewrite to python and publish as PYPU on PYPI

PYPU_REPO=${PYPU_REPO:-""}
PYPU_REPO_DIR=${PYPU_REPO_DIR:-""}

tmpdir=`mktemp -d /tmp/python-publish.XXXXXXXXX`
cd $tmpdir

function finish { 
  echo "Cleaning up"
  rm -rf $tmpdir
}
trap finish EXIT

project_name=$1
project_version=$2

set `cat ~/.netrc | grep '^machine code.google.com'`
machine=$2
login=$4
password=$6

if [ -n "$PYPU_REPO" ]; then
    git clone $PYPU_REPO .
elif [ -n "$PYPU_REPO_DIR" -a -d "${PYPU_REPO_DIR}/${project_name}/.git"  ]; then
    git clone ${PYPU_REPO_DIR}/${project_name} .
else
    git clone https://code.google.com/p/${project_name}/ .
fi
git checkout "v${project_version}" || exit 9
if [ "${project_version}" != "`python setup.py --version`"]; then
    echo "Checked out version and version shown by setup.py differ!"
    exit 8
fi
summary="$project_name $project_version - `git show -s --format=%N v${project_version} | head -n4 | tail -n1`"
dist_dir=$tmpdir/dist/
python setup.py sdist --dist-dir $dist_dir || exit 7
googlecode_upload.py -s "$summary" -p $project_name -u $login -w $password $dist_dir/*.tar.gz || exit 6
python setup.py register || exit 5